package com.evoupsight.monitorpass.gateway.handlers.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;
import java.util.List;

/**
 * @author evoup
 */
public class MessageDecoder extends ByteToMessageDecoder {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        Message message = new Message();
        message.setMagicNumber0(in.readByte());
        message.setMagicNumber1(in.readByte());
        message.setMagicNumber2(in.readByte());
        message.setMagicNumber3(in.readByte());
        // <MOND><version><length><body>
        if (message.getMagicNumber0() == 77 && message.getMagicNumber1() == 79 && message.getMagicNumber2() == 78 && message.getMagicNumber3() == 68) {
            message.setVersion(in.readByte());
            long length = in.readLongLE();
            message.setLength(length);
            CharSequence body = in.readCharSequence((int) length, Charset.defaultCharset());
            message.setBody(body.toString());
            out.add(message);
        } else {
            logger.debug("Skipping cookie with null name");
        }

    }
}
